package com.ruoyi.quartz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.basedata.domain.TerminalsXb;
import com.ruoyi.basedata.mapper.TerminalsXbMapper;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.datastatistics.domain.MeterHistoryData;
import com.ruoyi.datastatistics.domain.TerminalsFreezeXb;
import com.ruoyi.datastatistics.mapper.TerminalsFreezeMapper;
import com.ruoyi.datastatistics.mapper.TerminalsFreezeXbMapper;
import com.ruoyi.quartz.mapper.GenerateXbFreezeMapper;
import com.ruoyi.quartz.service.IGeneratetDataXbService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.OptionalDouble;

@Slf4j
@Service
public class GeneratetDataXbServiceImpl implements IGeneratetDataXbService {
    @Autowired
    private GenerateXbFreezeMapper generateXbFreezeMapper;
    @Autowired
    private TerminalsXbMapper terminalsXbMapper;

    @Autowired
    private TerminalsFreezeXbMapper terminalsFreezeXbMapper;

    //生成小表日冻结数据
    @Override
    public void GeneratetDayFreeze() {
        try {
            String today = DateUtil.getDayDate(0) + " 00:00:00";
            String yesterday = DateUtil.getDayDate(-1) + " 00:00:00";
            String beforeYesterday = DateUtil.getDayDate(-2) + " 00:00:00";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<TerminalsXb> terminalsXbList = terminalsXbMapper.selectList(new LambdaQueryWrapper<TerminalsXb>()
                    .eq(TerminalsXb::getLocationNb,"104221204056"));
            List<List<TerminalsXb>> lists = CollectionUtils.subListByCount(terminalsXbList, 100);
            for (List<TerminalsXb> terminalsXbs : lists) {
                List<TerminalsFreezeXb> list = new ArrayList<>();
                terminalsXbs.forEach(terminalsXb -> {
                    try {
                        List<MeterHistoryData> yesterdayHistory = generateXbFreezeMapper.selectHistoryByDate(terminalsXb.getLocationNb(), yesterday, today);
                        List<MeterHistoryData> beforeYesterdayHistory = generateXbFreezeMapper.selectHistoryByDate(terminalsXb.getLocationNb(), beforeYesterday, yesterday);
                        TerminalsFreezeXb terminalsFreezeXb = new TerminalsFreezeXb();
                        terminalsFreezeXb.setTenantId(terminalsXb.getTenantId());
                        terminalsFreezeXb.setSupplierId(terminalsXb.getSupplierId());
                        terminalsFreezeXb.setLocationNb(terminalsXb.getLocationNb());
                        terminalsFreezeXb.setFrozenType("day");
                        terminalsFreezeXb.setFreezeTime(DateUtil.getDayDate(-1));
                        terminalsFreezeXb.setCreateTime(new Date());
                        if (yesterdayHistory.size() == 0){
                            terminalsFreezeXb.setCopyRate(3);
                        }
                        if (yesterdayHistory.size() != 0 && beforeYesterdayHistory.size() != 0){
                            MeterHistoryData yesterdayData = yesterdayHistory.get(0);
                            MeterHistoryData beforeYesterdayData = beforeYesterdayHistory.get(0);
                            terminalsFreezeXb.setCopyRate(1);
                            terminalsFreezeXb.setCumulativeFlow(yesterdayData.getTotalFlow().subtract(beforeYesterdayData.getTotalFlow()));
                            OptionalDouble average = yesterdayHistory.stream().map(MeterHistoryData::getTerminalVol).mapToDouble(BigDecimal::doubleValue).average();
                            if (average.isPresent()){
                                terminalsFreezeXb.setTerminalVolAvg(BigDecimal.valueOf(average.getAsDouble()));
                            }
                            terminalsFreezeXb.setStartReading(beforeYesterdayData.getTotalFlow());
                            terminalsFreezeXb.setEndReading(yesterdayData.getTotalFlow());
                            terminalsFreezeXb.setStartReadingTime(sdf.parse(beforeYesterdayData.getReadDate()));
                            terminalsFreezeXb.setEndReadingTime(sdf.parse(yesterdayData.getReadDate()));
                        }
                        if (yesterdayHistory.size() != 0 && beforeYesterdayHistory.size() == 0){
                            MeterHistoryData yesterdayData = yesterdayHistory.get(0);
                            terminalsFreezeXb.setCopyRate(2);
                            terminalsFreezeXb.setEndReading(yesterdayData.getTotalFlow());
                            terminalsFreezeXb.setEndReadingTime(sdf.parse(yesterdayData.getReadDate()));
                        }
                        list.add(terminalsFreezeXb);
                    }catch (Exception e){
                        log.info("设备" + terminalsXb.getLocationNb() + "生成日冻结数据出错" + ExceptionUtil.getExceptionMessage(e));
                    }
                });
                if (list.size() > 0){
                    terminalsFreezeXbMapper.insertBatch(list);
                }
            }
        }catch (Exception e){
            log.info("定时任务生成小表日冻结数据出错" + ExceptionUtil.getExceptionMessage(e));
        }

    }

    public void GeneratetMonthFreeze(){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
            String lastMonthFirstDate = DateUtil.getLastMonthFirstDate(sdf.format(new Date()));
            String lastMonthEndDate = DateUtil.getLastMonthEndDate(sdf.format(new Date()));
            List<TerminalsXb> terminalsXbList = terminalsXbMapper.selectList(new LambdaQueryWrapper<TerminalsXb>());
            List<List<TerminalsXb>> lists = CollectionUtils.subListByCount(terminalsXbList, 100);
            for (List<TerminalsXb> terminalsXbs : lists) {
                List<TerminalsFreezeXb> list = new ArrayList<>();
                terminalsXbs.forEach(terminalsXb -> {
                    try {
                        List<MeterHistoryData> lastMonthData = generateXbFreezeMapper.selectHistoryByDate(terminalsXb.getLocationNb(), lastMonthFirstDate, lastMonthEndDate);
                        if (lastMonthData.size() > 1){
                            TerminalsFreezeXb terminalsFreezeXb = new TerminalsFreezeXb();
                            terminalsFreezeXb.setTenantId(terminalsXb.getTenantId());
                            terminalsFreezeXb.setSupplierId(terminalsXb.getSupplierId());
                            terminalsFreezeXb.setLocationNb(terminalsXb.getLocationNb());
                            terminalsFreezeXb.setFrozenType("month");
                            terminalsFreezeXb.setFreezeTime(sdf1.format(new Date()));
                            terminalsFreezeXb.setCreateTime(new Date());
                            MeterHistoryData endData = lastMonthData.get(0);
                            MeterHistoryData startData = lastMonthData.get(lastMonthData.size() - 1);
                            terminalsFreezeXb.setCumulativeFlow(endData.getTotalFlow().subtract(startData.getTotalFlow()));
                            OptionalDouble average = lastMonthData.stream().map(MeterHistoryData::getTerminalVol).mapToDouble(BigDecimal::doubleValue).average();
                            if (average.isPresent()){
                                terminalsFreezeXb.setTerminalVolAvg(BigDecimal.valueOf(average.getAsDouble()));
                            }
                            terminalsFreezeXb.setStartReading(startData.getTotalFlow());
                            terminalsFreezeXb.setEndReading(endData.getTotalFlow());
                            terminalsFreezeXb.setStartReadingTime(sdf.parse(startData.getReadDate()));
                            terminalsFreezeXb.setEndReadingTime(sdf.parse(endData.getReadDate()));
                            list.add(terminalsFreezeXb);
                        }
                    }catch (Exception e){
                        log.info("设备" + terminalsXb.getLocationNb() + "生成月冻结数据出错" + ExceptionUtil.getExceptionMessage(e));
                    }
                });
                if (list.size() > 0){
                    terminalsFreezeXbMapper.insertBatch(list);
                }
            }
        }catch (Exception e){
            log.info("定时任务生成小表月冻结数据出错" + ExceptionUtil.getExceptionMessage(e));
        }

    }

    @Override
    public void GeneratetbWxXb() {

    }


}
